﻿package net.wangit.adm.admin;

import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.context.LocalContext;
import net.wangit.support.UnitInterceptor;
import net.wangit.user.admin.Admin;
import net.wangit.user.admin.AdminFactory;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;
import net.wangit.view.unit.UnitComponent;

public class AdminAuthUI implements UnitInterceptor {

	private static final String DOMAIN = "net.wangit.adm.admin.AdminAuthUI.domain";
	private static final String ADMINISTRATOR_ID = "net.wangit.adm.admin.AdminAuthUI.adminid";

	public AdminAuthUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String aid = getAndSetAdministratorId();
		if (Checker.isEmpty(aid)) {
			return "no administrator was specified!";
		} else {
			Admin administrator = AdminFactory.getAdmin(aid);
			unit.setTitle((new StringBuilder(String
					.valueOf(((UnitComponent) unit).getTitle()))).append(" - ")
					.append(administrator.getName()).append("(").append(aid)
					.append(")").toString());
			unit.getElement("domain").setDefaultValue(getAndSetDomain());
			unit.getElement("adminid").setDefaultValue(aid);
			Tree oTree = (Tree) unit.getElement("organizations").getObject();
			unit.getElement("organization").setName(
					(new StringBuilder(" (")).append(
							administrator.getOrganizations().length)
							.append("/").append(oTree.size()).append(")")
							.toString());
			Tree gTree = (Tree) unit.getElement("groups").getObject();
			unit.getElement("group").setName(
					(new StringBuilder(" (")).append(
							administrator.getGroups().length).append("/")
							.append(gTree.size()).append(")").toString());
			Tree rTree = (Tree) unit.getElement("roles").getObject();
			unit.getElement("role").setName(
					(new StringBuilder(" (")).append(
							administrator.getRoles().length).append("/")
							.append(administrator.getIndirectRoles().length)
							.append(") (").append(
									administrator.getAllRolesCount()).append(
									"/").append(rTree.size()).append(")")
							.toString());
			unit.getElement("privilege").setName(
					(new StringBuilder(" (")).append(
							administrator.getPrivileges().size()).append(")")
							.toString());
			return unit.write(ac);
		}
	}

	public static String getAndSetDomain() {
		ActionContext ac = LocalContext.getLocalContext().getActionContext();
		return ActionContextHelper.getRequest2Session(ac,
				"admin.authorization.domain",
				"net.wangit.adm.admin.AdminAuthUI.domain", "app");
	}

	public static String getAndSetAdministratorId() {
		ActionContext ac = LocalContext.getLocalContext().getActionContext();
		return ActionContextHelper.getRequest2Session(ac, "adminid",
				"net.wangit.adm.admin.AdminAuthUI.adminid", null);
	}
}
